package com.gensdai.leliang.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.flyco.roundview.RoundTextView;
import com.gensdai.leliang.AppApplication;
import com.gensdai.leliang.R;
import com.gensdai.leliang.adapter.ProductDetailDescListAdapter;
import com.gensdai.leliang.base.BaseActivity;
import com.gensdai.leliang.common.bean.CommentInfoBean;
import com.gensdai.leliang.dialog.DialogPopup;
import com.gensdai.leliang.dialog.Select_Share;
import com.gensdai.leliang.entity.parseBean.BaseParse;
import com.gensdai.leliang.entity.parseBean.OrderPreperBean;
import com.gensdai.leliang.entity.parseBean.ParentBean;
import com.gensdai.leliang.entity.parseBean.ProductAttributesListBean;
import com.gensdai.leliang.entity.parseBean.ProductInfo;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.remoteInterface.URLConfig;
import com.gensdai.leliang.retrofitUtils.BaseObserver;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.gensdai.leliang.utils.PreferencesUtils;
import com.gensdai.leliang.view.ColoredRatingBar;
import com.gensdai.leliang.view.NoScrollListView;
import com.gensdai.leliang.view.ScrollChangedScrollView;
import com.gensdai.leliang.view.Toaster;
import com.gensdai.leliang.view.banner.PageInfo;
import com.gensdai.leliang.view.banner.SimpleImageBanner;
import com.gensdai.leliang.view.listener.TranslucentListener;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.io.IOException;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.imkarl.waitview.WaitViewController;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

//商品详情页面
public class ProductDetail extends BaseActivity implements DialogPopup.OnPayItemClick, View.OnClickListener, TranslucentListener {

    public static final String EXTRA_PID = "PID";

    @BindView(R.id.ProductGalley)
    SimpleImageBanner ProductGalley;
    @BindView(R.id.selectTypeLayout)
    RelativeLayout selectTypeLayout;
    @BindView(R.id.product_title)
    TextView productTitle;
    @BindView(R.id.price)
    TextView price;
    @BindView(R.id.oldprice)
    TextView oldprice;
    @BindView(R.id.kuaiduprice)
    TextView kuaiduprice;
    @BindView(R.id.outnumber)
    TextView outnumber;
    @BindView(R.id.chandi)
    TextView chandi;
    @BindView(R.id.phone)
    TextView phone;


    DialogPopup property = null;
    @BindView(R.id.paycart)
    TextView paycart;
    @BindView(R.id.pay)
    TextView pay;


    ProductInfo p;
    @BindView(R.id.productDescImg)
    NoScrollListView productDescImg;
    @BindView(R.id.detailRootview)
    ScrollChangedScrollView detailRootview;
    @BindView(R.id.feature1)
    TextView feature1;
    @BindView(R.id.featureLayout1)
    LinearLayout featureLayout1;
    @BindView(R.id.feature2)
    TextView feature2;
    @BindView(R.id.featureLayout2)
    LinearLayout featureLayout2;
    @BindView(R.id.feature3)
    TextView feature3;
    @BindView(R.id.featureLayout3)
    LinearLayout featureLayout3;
    @BindView(R.id.feature4)
    TextView feature4;
    @BindView(R.id.featureLayout4)
    LinearLayout featureLayout4;

    @BindView(R.id.comment_icon)
    SimpleDraweeView comment_icon;
    @BindView(R.id.commentLable)
    TextView commentLable;
    @BindView(R.id.commentTotalNum)
    TextView commentTotalNum;
    @BindView(R.id.commentName)
    TextView commentName;
    @BindView(R.id.commentRating)
    ColoredRatingBar commentRating;
    @BindView(R.id.comment_head_layout)
    LinearLayout commentHeadLayout;
    @BindView(R.id.comment_content)
    TextView commentContent;
    @BindView(R.id.comment_attribute)
    TextView commentAttribute;
    @BindView(R.id.toCommentActBtn)
    RoundTextView toCommentActBtn;
    @BindView(R.id.offlineView)
    TextView offlineView;


    @BindView(R.id.baby_lable_icon)
    ImageView babyLableIcon;
    @BindView(R.id.baby_lable_text)
    TextView babyLableText;
    @BindView(R.id.baby_lable)
    LinearLayout babyLable;
    @BindView(R.id.comment_lable_icon)
    ImageView commentLableIcon;
    @BindView(R.id.comment_lable_text)
    TextView commentLableText;
    @BindView(R.id.comment_lable)
    LinearLayout commentTopLable;
    @BindView(R.id.detail_lable_icon)
    ImageView detailLableIcon;
    @BindView(R.id.detail_lable_text)
    TextView detailLableText;
    @BindView(R.id.detail_lable)
    LinearLayout detailLable;
    @BindView(R.id.recommend_lable_icon)
    ImageView recommendLableIcon;
    @BindView(R.id.recommend_lable_text)
    TextView recommendLableText;
    @BindView(R.id.recommend_lable)
    LinearLayout recommendLable;
    @BindView(R.id.maodian_comment)
    RelativeLayout maodianComment;
    @BindView(R.id.maodian_detail)
    RelativeLayout maodianDetail;
    @BindView(R.id.top_menu_bar)
    LinearLayout topMenuBar;


    private String pid = "";
    private String userid = "";

    Select_Share share;
    Tencent mTencent;
    KProgressHUD hud;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        pid = getIntent().getStringExtra(EXTRA_PID);
        userid = PreferencesUtils.getStringPreference(this, OrderPreperActivity.prefreceName, OrderPreperActivity.prefrece_userid, ""); //获取用户id没有登陆就是没有
        mTencent = Tencent.createInstance("1106232764", this.getApplicationContext());
        share = new Select_Share(this);
        hud = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在处理...")
                .setCancellable(true)
                .setAnimationSpeed(1)
                .setDimAmount(0.5f);
        WaitViewController.from(detailRootview).renderChilds();
        initData(pid);
        installListener();
//        comment_icon.setImageURI(Uri.parse("http://img2.imgtn.bdimg.com/it/u=678448208,3316568922&fm=26&gp=0.jpg"));
    }

    //初始化banner
    private void initViewPager(List<String> imgs) {
        List<PageInfo> infos = new ArrayList<>();
//        PageInfo pageinfo = new PageInfo();
//        pageinfo.setImgPath(imgs.get(0));
//        pageinfo.setType("video");
//        infos.add(pageinfo);

        for (String s : imgs) {
            PageInfo pf = new PageInfo();
            pf.setImgPath(s);
            pf.setType("image");
            infos.add(pf);
        }

//        PageInfo i1 = new PageInfo();
//        i1.setImgPath("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496281761&di=ad9155035cccb665737ea5f8c181c983&imgtype=jpg&er=1&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F011f3755dd54456ac7251df80a7837.jpg%40900w_1l_2o_100sh.jpg");
//        infos.add(i1);
//        PageInfo i2 = new PageInfo();
//        i2.setImgPath("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1495687112967&di=0f6315606c198beced1e746d3a08d20c&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01f8e4565c6a866ac7253403651e79.png%40900w_1l_2o_100sh.jpg");
//        infos.add(i2);
        ProductGalley.setSource(infos).startScroll();
    }


    //打开选择商品类型的窗口
    private void openPropertyWindow() {
        if (property != null) {
            property.showPopupWindow();
        }

    }


    private void initData(String id) {
        String uno = PreferencesUtils.getStringPreference(this, OrderPreper2Activity.prefreceName, "userno", "");
        Map<String, String> detailParams = new HashMap<>();
        detailParams.put("product_relation_id", id);
        detailParams.put("userid", userid);
        detailParams.put("userNo", uno);
        getProductDetail(detailParams);
    }


    @OnClick(R.id.shareIcon)
    public void onShareClick(View v) {
        if (p != null) {
            share.show();
        }
    }

    private void getProductDetail(Map<String, String> params) {

        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().getProductDetail(params))
                .compose(this.<BaseParse<ProductInfo>>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribe(new BaseObserver<ProductInfo>(this) {
                    @Override
                    public void onHandleSuccess(ProductInfo productInfo) {
                        //处理得到的数据
                        resultData(productInfo);
                    }

                    @Override
                    public void onHandleError(int code, String message) {

                    }
                });
    }


    private void resultData(ProductInfo s) {
        if (s != null) {
            if (s.getState() == 3) {
                //如果商品是删除状态就直接finish掉
                Toaster.showOneToast("该商品已被商家删除，请选择其他商品");
                this.finish();
            } else if (s.getState() == 2) {
                //是下架状态  显示下架的view 按钮灰色
                paycart.setTextColor(0x80ffffff);
                pay.setTextColor(0x80ffffff);
                offlineView.setVisibility(View.VISIBLE);
            } else if (s.getState() == 0) {
                //编辑状态
                Toaster.showOneToast("该商品正在被商家修改中，请稍后查看该商品");
                this.finish();
            } else {
                offlineView.setVisibility(View.GONE);
                paycart.setTextColor(0xffffffff);
                pay.setTextColor(0xffffffff);
                selectTypeLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        openPropertyWindow();
                    }
                });
                paycart.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        openPropertyWindow();
                    }
                });
                pay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        openPropertyWindow();
                    }
                });
            }
            //填充数据
            p = s;
            productTitle.setText(p.getProductName());
//            price.setText(AppApplication.getContext().getString(R.string.rmb2) + p.getNowPrice());
            //如果价格相同就显示一个价格
            if (TextUtils.equals(p.getLowestPrice(), p.getHighestPrice())) {
                price.setText(AppApplication.getContext().getString(R.string.rmb2) + p.getLowestPrice());
            } else {
                price.setText(AppApplication.getContext().getString(R.string.rmb2) + p.getLowestPrice() + "~" + p.getHighestPrice());
            }
            oldprice.setText(AppApplication.getContext().getString(R.string.rmb2) + p.getOriginalPrice());
            // 设置中划线并加清晰
            oldprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
            kuaiduprice.setText(String.format(this.getResources().getString(R.string.kuaidi_price), p.getExpressFee()));
            chandi.setText(p.getSendAdrProv() + "" + p.getSendAdrCity());
            outnumber.setText(String.format(this.getResources().getString(R.string.soldnum), p.getSoldNum()));

            if (p.getCommentInfo() != null) {
                initCommentLayout(p.getCommentInfo());
            }
            //设置图片第一张为logo
            if (p.getLogoPhotos() != null && p.getLogoPhotos().size() > 0) {
                p.setLogo(p.getLogoPhotos().get(0));
                initViewPager(p.getLogoPhotos());
            }
            if (p.getProductAttributesList() != null) {
                initAttributesView(p.getProductAttributesList(), p.getLogoPhotos() != null && p.getLogoPhotos().size() > 0 ? p.getLogoPhotos().get(0) : "");
            }
            if (p.getDescrPhotos() != null) {
                initDescImg(p.getDescrPhotos());
            }

            //初始化产品的特点 例如满多少包邮
            if (!TextUtils.isEmpty(s.getFeature1())) {
                featureLayout1.setVisibility(View.VISIBLE);
                feature1.setText(s.getFeature1());
            }
            if (!TextUtils.isEmpty(s.getFeature2())) {
                featureLayout2.setVisibility(View.VISIBLE);
                feature2.setText(s.getFeature2());
            }
            if (!TextUtils.isEmpty(s.getFeature3())) {
                featureLayout3.setVisibility(View.VISIBLE);
                feature3.setText(s.getFeature3());
            }
            if (!TextUtils.isEmpty(s.getFeature4())) {
                featureLayout4.setVisibility(View.VISIBLE);
                feature4.setText(s.getFeature4());
            }


            if (p.getIfHasCollected() != null) {
                if (TextUtils.equals("1", p.getIfHasCollected())) {
                    isfav = true;
                } else {
                    isfav = false;
                }
            }

            getSupportActionBar().invalidateOptionsMenu();

            WaitViewController.from(detailRootview).removeChilds();
        }
    }

    private void initCommentLayout(CommentInfoBean info) {
        Uri uri = Uri.parse("");

        if (TextUtils.isEmpty(info.commentTotalNum) || TextUtils.equals("0", info.commentTotalNum)) {
            commentLable.setText("暂无评论");
            toCommentActBtn.setVisibility(View.GONE);
            commentTotalNum.setText("(" + 0 + ")");
            comment_icon.setVisibility(View.GONE);
        } else {
            commentTotalNum.setText("(" + info.commentTotalNum + ")");
            commentLable.setText("宝贝评价");
            toCommentActBtn.setVisibility(View.VISIBLE);

            if (!TextUtils.isEmpty(info.handpic)) {
                if (info.handpic.length() > 5) {
                    if (!info.handpic.substring(0, 4).contains("http") || !info.handpic.substring(0, 4).contains("https")) {
                        info.handpic = URLConfig.BASEDOMAIN + info.handpic;
                    }
                }
                uri = uri.parse(info.handpic);
                comment_icon.setVisibility(View.VISIBLE);
            }
            comment_icon.setImageURI(uri);
        }

        if (!TextUtils.isEmpty(info.attributeName)) {
            commentAttribute.setVisibility(View.VISIBLE);
            commentAttribute.setText(info.attributeName);
        } else {
            commentAttribute.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(info.commentInfo)) {
            commentContent.setVisibility(View.VISIBLE);
            commentContent.setText(info.commentInfo.trim());
        } else {
            commentContent.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(info.nickname)) {
            commentName.setVisibility(View.VISIBLE);
            commentName.setText(info.nickname);
        } else {
            commentName.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(info.avgScore)) {
            commentRating.setVisibility(View.VISIBLE);
            commentRating.setRating(Float.valueOf(info.avgScore));
        } else {
            commentRating.setVisibility(View.GONE);
        }

        toCommentActBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(ProductDetail.this, ActivityCommentList.class);
                it.putExtra(ActivityCommentList.EXTRA_RELATIONID, pid);
                startActivity(it);
            }
        });
    }

    private void initDescImg(List<String> imgs) {

        ProductDetailDescListAdapter adapter = new ProductDetailDescListAdapter(this);
        productDescImg.setAdapter(adapter);
        adapter.initAdd(imgs);

        ProductGalley.setFocusable(true);
        ProductGalley.setFocusableInTouchMode(true);
        ProductGalley.requestFocus();
    }

    private void initAttributesView(List<ProductAttributesListBean> list, String img) {
        property = new DialogPopup(ProductDetail.this);
        property.setBackPressEnable(true);
        property.setOnPayItemClick(this);
        property.setData(list, img);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.product_detail_menu, menu);
        final MenuItem collItem = menu.findItem(R.id.action_collection);
        collItem.getActionView().findViewById(R.id.collctionText).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeCollction();
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.action_collection:
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    boolean isfav = false;

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        attrCollctionImg(menu.findItem(R.id.action_collection));
        return super.onPrepareOptionsMenu(menu);
    }

    private void attrCollctionImg(MenuItem item) {
        ImageView img = (ImageView) item.getActionView().findViewById(R.id.collctionImg);
        TextView text = (TextView) item.getActionView().findViewById(R.id.collctionText);
        if (isfav) {
            text.setText("已收藏");
            img.setImageResource(R.mipmap.collction_press);
        } else {
            text.setText("收藏");
            img.setImageResource(R.mipmap.collection_normal);
        }
    }

    private void changeCollction() {

        String uno = PreferencesUtils.getStringPreference(this, OrderPreper2Activity.prefreceName, "userno", "");

        if (TextUtils.isEmpty(uno)) {
            //用户ID为空 跳到登录界面
            Toaster.showOneToast("用户未登陆，请登陆后操作");
            startActivity(new Intent(this, user_enter.class));
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("userNo", uno);
        params.put("productRelationId", pid);
        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().CollctionGoods(params))
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }
                        if (hud != null && !hud.isShowing()) {
                            hud.show();
                        }
                        Log.d("accept", "accept");
                    }
                })
                .subscribe(new BaseObserver<String>(this) {
                    @Override
                    public void onRequestEnd() {
                        super.onRequestEnd();
                        if (hud != null && hud.isShowing()) {
                            hud.dismiss();
                        }
                    }

                    @Override
                    public void onHandleSuccess(String s) {

                    }

                    @Override
                    public void onHandleMessageSuccess(String s, String message) {
                        super.onHandleMessageSuccess(s, message);
                        if (!TextUtils.isEmpty(s)) {
                            if (TextUtils.equals("1", s)) {
                                isfav = true;
                            } else {
                                isfav = false;
                            }
                        }

                        getSupportActionBar().invalidateOptionsMenu();
                        Toaster.showOneToast(message);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        Toaster.showOneToast(message);
                        invalidateOptionsMenu();
                    }
                });
    }


    /*点击购买按钮后的操作*/
    @Override
    public void OnPayClick(ProductAttributesListBean currentBean, int number) {

        Intent it = new Intent(this, OrderPreper3Activity.class);
//        it.putExtra(OrderPreperActivity.EXTRA_PRODUCT, PG.convertParcelable(p));
//        it.putExtra(OrderPreperActivity.EXTRA_ATTRIBUT, PG.convertParcelable(currentBean));
//        it.putExtra(OrderPreperActivity.EXTRA_NUM, number);

        userid = PreferencesUtils.getStringPreference(this, OrderPreper2Activity.prefreceName, OrderPreper2Activity.prefrece_userid, ""); //获取用户id没有登陆就是没有
        if (TextUtils.isEmpty(userid)) {
            //用户ID为空 跳到登录界面
            startActivity(new Intent(this, user_enter.class));
            return;
        }


        OrderPreperBean orderBean = new OrderPreperBean();
        orderBean.setP(p);
        orderBean.setAttributes(currentBean);
        orderBean.setNumber(number);

        ArrayList<OrderPreperBean> order = new ArrayList<>();
        order.add(orderBean);
        Bundle bd = new Bundle();
        bd.putSerializable(OrderPreperActivity.EXTRA_PRODUCT, (Serializable) order);
        it.putExtras(bd);
        it.putExtra(OrderPreperActivity.EXTRA_FROM_FLAG, "2");
        startActivity(it);
    }

    @Override
    public void OnPayCartClick(ProductAttributesListBean currentBean, int number) {
        postCart(currentBean, number);
    }


    private void postCart(ProductAttributesListBean currentBean, int number) {
        Map<String, String> params = new HashMap<>();
        params.put("prodRelaId", currentBean.getProductRelationId());
        params.put("prodAttrId", currentBean.getId());
        params.put("prodSum", number + "");
        ApiService.getInstance(this).addShopCar(params)//涉及到IO操作
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }
                        if (hud != null) {
                            hud.show();
                        }
                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ParentBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();
                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull ParentBean s) {
                        //处理得到的数据
                        if (s.isSuccess()) {
                            Toaster.showOneToast(s.getMessage());
                        } else {
                            if (s.getCode() == 314) {
                                Toaster.showOneToast(s.getMessage());
                                startActivity(new Intent(ProductDetail.this, user_enter.class));
                            } else {
                                Toaster.showOneToast(s.getMessage());
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
//                        Toast.makeText(AppApplication.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        if (e.getMessage() != null) {

                            Toaster.showOneToast(e.getMessage());
                        }
                        if (hud != null && hud.isShowing()) {

                            hud.dismiss();
                        }
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        if (hud != null && hud.isShowing()) {

                            hud.dismiss();
                        }
                    }
                });
    }


    /**
     * 分享到QQ
     */
    private void onClickShare() {
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
                QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, "【乐粮乐成长】" + p.getProductName());
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "不剁手就可以买的宝贝");
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,
                p.getShareLinks()
                        + "&userNo=" + getSharedPreferences("User", MODE_PRIVATE).getString("userno", ""));
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, p.getThumpicPhotos());
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "乐粮乐成长");
        // params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, "其他附加功能");
        mTencent.shareToQQ(this, params, new BaseUiListener());
    }


    IWXAPI wxApi;

    /**
     * 分享到微信
     */
    private void onClickShareWX(final int flag) {
        wxApi = WXAPIFactory.createWXAPI(this, AppApplication.APPID);
        wxApi.registerApp(AppApplication.APPID);

        new Thread(new Runnable() {
            @Override
            public void run() {
                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl = p.getShareLinks()
                        + "&userNo=" + getSharedPreferences("User", MODE_PRIVATE).getString("userno", "");
                WXMediaMessage msg = new WXMediaMessage(webpage);
                msg.title = "【乐粮乐成长】" + p.getProductName();
                msg.description = "不剁手就可以买的宝贝";
                //这里替换一张自己工程里的图片资源
                Bitmap thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.app_logo);
                ;
                try {
                    Bitmap thumb = BitmapFactory.decodeStream(new URL(p.getThumpicPhotos()).openStream());
                    //注意下面的这句压缩，120，150是长宽。
                    //一定要压缩，不然会分享失败
                    thumbBmp = Bitmap.createScaledBitmap(thumb, 120, 150, true);
                    //Bitmap回收
                    thumb.recycle();


                    msg.setThumbImage(thumbBmp);
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = String.valueOf(System.currentTimeMillis());
                    req.message = msg;
                    req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
                    wxApi.sendReq(req);

                } catch (IOException e) {

                }
            }
        }).start();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.qq:
                onClickShare();
                break;
            case R.id.wx:
                onClickShareWX(0);
                break;
            case R.id.wxpyq:
                onClickShareWX(1);
                break;
            case R.id.cancel:
                share.dismiss();
                break;
            default:
                break;
        }
    }

    private class BaseUiListener implements IUiListener {

        @Override
        public void onCancel() {
            // TODO Auto-generated method stub
            Toaster.showOneToast("取消了分享");
        }

        @Override
        public void onComplete(Object arg0) {
            // TODO Auto-generated method stub
            Toaster.showOneToast("分享成功");
        }

        @Override
        public void onError(UiError arg0) {
            // TODO Auto-generated method stub
            Toaster.showOneToast("分享出现了一个问题");
        }
    }


    /**
     * 是否是ScrollView主动动作
     * false:是ScrollView主动动作
     * true:是TabLayout 主动动作
     */
    private boolean tagFlag = false;
    /**
     * 用于切换内容模块，相应的改变导航标签，表示当一个所处的位置
     */
    private int lastTagIndex = 0;
    /**
     * 用于在同一个内容模块内滑动，锁定导航标签，防止重复刷新标签
     * true: 锁定
     * false ; 没有锁定
     */
    private boolean content2NavigateFlagInnerLock = false;

    // 计算点击的导航标签所对应内容区域的高度
    int targetY = 0;

    private void installListener() {
        detailRootview.setTranslucentListener(this);
        detailRootview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //表明当前的动作是由 ScrollView 触发和主导
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    tagFlag = true;
                }
                return false;
            }
        });

        detailRootview.setScrollViewListener(new ScrollChangedScrollView.ScrollViewListener() {

            @Override
            public void onScrollChanged(ScrollView scrollView, int x, int y, int oldx, int oldy) {
                scrollRefreshNavigationTag(scrollView);
            }

            @Override
            public void onScrollStop(boolean isStop) {
            }
        });


        babyLable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //表明当前的动作是由 TabLayout 触发和主导
                tagFlag = false;
                targetY = ProductGalley.getTop();
                detailRootview.smoothScrollTo(0, targetY - getResources().getDimensionPixelSize(R.dimen.px98dp) + 5);
                checkTopLable(0);
            }
        });
        commentTopLable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //表明当前的动作是由 TabLayout 触发和主导
                tagFlag = false;
                targetY = maodianComment.getTop();
                detailRootview.smoothScrollTo(0, targetY - getResources().getDimensionPixelSize(R.dimen.px98dp) + 5);
                checkTopLable(1);
            }
        });
        detailLable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //表明当前的动作是由 TabLayout 触发和主导
                tagFlag = false;
                targetY = maodianDetail.getTop();
                detailRootview.smoothScrollTo(0, targetY - getResources().getDimensionPixelSize(R.dimen.px98dp) + 5);
                checkTopLable(2);
            }
        });
        recommendLable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkTopLable(3);
            }
        });

    }

    /**
     * 内容区域滑动刷新导航标签
     *
     * @param scrollView 内容模块容器
     */
    private void scrollRefreshNavigationTag(ScrollView scrollView) {
        if (scrollView == null) {
            return;
        }

        // 获得ScrollView滑动距离
        int scrollY = scrollView.getScrollY();
        // 确定ScrollView当前展示的顶部内容属于哪个内容模块
        if (scrollY > maodianDetail.getTop() - getResources().getDimensionPixelSize(R.dimen.px98dp)) {
            refreshContent2NavigationFlag(2);
        } else if (scrollY > maodianComment.getTop() - getResources().getDimensionPixelSize(R.dimen.px98dp)) {
            refreshContent2NavigationFlag(1);
        } else {
            refreshContent2NavigationFlag(0);
        }
    }

    /**
     * 刷新标签
     *
     * @param currentTagIndex 当前模块位置
     */
    private void refreshContent2NavigationFlag(int currentTagIndex) {
        // 上一个位置与当前位置不一致是，解锁内部锁，是导航可以发生变化
//        if (lastTagIndex != currentTagIndex) {
//            content2NavigateFlagInnerLock = false;
//        }
//        if (!content2NavigateFlagInnerLock) {
//            // 锁定内部锁
//            content2NavigateFlagInnerLock = true;
//            // 动作是由ScrollView触发主导的情况下，导航标签才可以滚动选中
//            if (tagFlag) {
//                checkTopLable(currentTagIndex);
//            }
//        }
//        lastTagIndex = currentTagIndex;

        checkTopLable(currentTagIndex);
    }

    //依次更改viwe
    private void checkTopLable(int position) {
        lastTagIndex = position;
        babyLableIcon.setVisibility(View.INVISIBLE);
        commentLableIcon.setVisibility(View.INVISIBLE);
        detailLableIcon.setVisibility(View.INVISIBLE);
        recommendLableIcon.setVisibility(View.INVISIBLE);

        babyLableText.setTextColor(getResources().getColor(R.color.producttitleColor));
        commentLableText.setTextColor(getResources().getColor(R.color.producttitleColor));
        detailLableText.setTextColor(getResources().getColor(R.color.producttitleColor));
        recommendLableText.setTextColor(getResources().getColor(R.color.producttitleColor));


        switch (position) {
            case 0:
                babyLableIcon.setVisibility(View.VISIBLE);
                babyLableText.setTextColor(getResources().getColor(R.color.product_top_tab_color));
                break;
            case 1:
                commentLableIcon.setVisibility(View.VISIBLE);
                commentLableText.setTextColor(getResources().getColor(R.color.product_top_tab_color));
                break;
            case 2:
                detailLableIcon.setVisibility(View.VISIBLE);
                detailLableText.setTextColor(getResources().getColor(R.color.product_top_tab_color));
                break;
            case 3:
                recommendLableIcon.setVisibility(View.VISIBLE);
                recommendLableText.setTextColor(getResources().getColor(R.color.product_top_tab_color));
                break;
            default:
                break;
        }
    }

    @Override
    public void onTranlucent(float alpha) {
        topMenuBar.setAlpha(alpha);
    }

    @Override
    protected String getTitleStr() {
        return "商品详情";
    }

    @Override
    protected boolean isShowBackButton() {
        return true;
    }

    @Override
    protected boolean isCustomTitle() {
        return false;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_product_detail;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
}
